<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose" width="850">
    <div class="wrapper"
      v-if="variableAtt?.dataType?.includes('variable_string') && variableAtt?.dataType != 'variable_string_relationFileName' && !isFormula">
      <el-input v-model="originVal" disabled style="margin-bottom: 12px;" />
      <el-input v-model="codeVal" placeholder="请输入文件code" style="margin-bottom: 12px;"
        v-if="variableAtt?.dataType === 'variable_string_quote'" />
      <el-input v-model="inputVal" placeholder="请输入值" />
      <el-button type="text" @click="handleAllReplace">全局替换</el-button>
    </div>
    <div class="wrapper" v-if="variableAtt?.dataType == 'variable_string_relationFileName' && !isFormula">
      <el-table :data="tableData" highlight-current-row @current-change="handleSelectionChange">
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column prop="fileCode" label="文件编号"> </el-table-column>
        <el-table-column prop="fileName" label="文件名称"> </el-table-column>
      </el-table>
    </div>
    <div class="replace-img" v-if="variableAtt?.dataType === 'variable_img' && !isFormula">
      <el-upload class="upload-demo" :headers="headers" drag :on-success="handleImgSuccess" :action="imgUploadUrl"
        :limit="1">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
    </div>
    <div class="wrapper" v-if="isFormula">
      <el-select v-model="chooseFormula">
        <el-option v-for="item in formulaList" :label="item.name" :value="item.number"></el-option>
      </el-select>
    </div>
    <div class="wrapper" v-if="isPic">
      <el-select v-model="choosePic">
        <el-option v-for="item in picList" :label="item.name" :value="item.number"></el-option>
      </el-select>
    </div>
    <div class="wrapper" v-if="isTable">
      <el-select v-model="chooseTable">
        <el-option v-for="item in tableList" :label="item.name" :value="item.number"></el-option>
      </el-select>
    </div>
    <iframe :src="baseURL" style="border: none; width: 850px; height: 500px;" ref="formulaRef"
      v-if="variableAtt?.dataType?.includes('_formula')"></iframe>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="handleClose">取 消</el-button>
      <el-button size="mini" type="primary" @click="handleConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import tinymce from "tinymce/tinymce";
  import { v4 as uuid } from 'uuid';
  import { getToken } from "@/utils/auth";
  import { refreshFigureNumbers } from '@/utils/plugins/image/figureSetting.js'
  import { saveVeriableValue, loadVaribles } from '@/api/computingConfig.js'
  import { getTemplateInfo } from "@/api/business";
  export default {
    name: "VariableRepalceDialog",
    data() {
      return {
        dialogVisible: false,
        title: "替换变量值",
        inputVal: "",
        codeVal: '',
        variableAtt: {},
        originVal: '',
        baseURL: tinymce.baseURL + '/tinymce/plugins/kityformula/index.html',
        imgUploadUrl: process.env.VUE_APP_BASE_API + "/editor/file/upload", // 上传的图片服务器地址
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // imgSrc:window.location.origin + '/prod-api/editor/file/download/'
        imgSrc: 'http://172.16.41.11/prod-api/editor/file/download/',
        currentRow: null,
        tableData: [],
        isFormula: false,
        formulaList: [],
        chooseFormula: "",
        formulaNode: null,
        editData: null,
        formaluaEditeType: 'add',
        orgTextVal: '',
        picList:[],
        isPic:false,
        choosePic:"",
        tableList:[],
        isTable:false,
        chooseTable:""
      };
    },
    watch: {
      dialogVisible(val) {
        if (val) {
          this.variableAtt = this.$store.state.xmleditor.variableAtt;
        }
      },
    },
    mounted() {
      const that = this
      window.addEventListener('message', function (event) {
        that.handleMessage(event.data)
      });

    },
    methods: {
      async show() {
        if (this.$store.state.xmleditor.editorConfig.editContentType == 'template') {
          getTemplateInfo(this.$store.state.xmleditor.docInfo.id).then((res) => {
            this.editData = res.data
          })
        }
        const { dataId, variableId ,dataType} = this.$store.state.xmleditor.variableAtt
        const formulas = tinymce.activeEditor.dom.select(`[data-type='formula']`);
        const figures = tinymce.activeEditor.dom.select(`[data-type='figure']`);
        const tables = tinymce.activeEditor.dom.select(`[data-type='table']`);
        this.formulaNode = tinymce.activeEditor.dom.select(`[data-id="${dataId}"]`)[0];

        if (this.$store.state.xmleditor.editorConfig.editContentType == 'template' && this.formulaNode && dataType.includes('variable_hide_string_formula')) {
          this.isFormula = true;
          this.formulaList = [];
          formulas.forEach(el => {
            const number = el.getAttribute('data-formula-number');
            this.formulaList.push({ name: `公式${number}`, number: number, dataId: el.getAttribute('data-id'), latex: el.getAttribute('data-latex') })
          })
        }
        if (this.$store.state.xmleditor.editorConfig.editContentType == 'template' && this.formulaNode && dataType.includes('variable_hide_string_pic')) {
          this.isPic = true;
          this.picList = [];
          figures.forEach(el => {
            const number = el.getAttribute('data-number');
            this.picList.push({ name: `图${number}`, number: number, dataId: el.getAttribute('data-id')})
          })
        }
        if (this.$store.state.xmleditor.editorConfig.editContentType == 'template' && this.formulaNode && dataType.includes('variable_hide_string_algo_table')) {
          this.isTable = true;
          this.tableList = [];
          tables.forEach(el => {
            const number = el.getAttribute('data-number');
            this.tableList.push({ name: `表格${number}`, number: number, dataId: el.getAttribute('data-id')})
          })
        }
        const variableNode = tinymce.activeEditor.dom.select(`span[data-id="${dataId}"]`)[0]
        this.originVal = variableNode.innerText
        this.inputVal = ''
        this.codeVal = ''
        // 依据性文件加载数据
        if (this.$store.state.xmleditor.variableAtt?.dataType == 'variable_string_relationFileName') {
          const allVariableContent = this.$store.state.xmleditor.allVariableContent || [];
          const queryParams = await allVariableContent.filter(item => {
            return item.variableCode == 'relationFiles'
          })

          await loadVaribles({ docNo: this.$store.state.xmleditor.docInfo.docNo, ids: [Number.parseInt(queryParams[0]?.id)] }).then(res => {
            if (res) {
              this.tableData = res?.data[0]?.variableContent?.data || [];
            }
          })
        }
        this.dialogVisible = true;
      },
      // 选择当前数据
      handleSelectionChange(val) {
        if (val) {
          if (this.currentRow) {
            this.currentRow = null;
          } else {
            this.currentRow = val;
          }
        }
      },
      //数组去重
      uniqueObjects(arr, key, key1) {
        const seen = new Set();
        const seen1 = new Set();
        return arr.filter(item => {
          const itemKey = item[key];
          const itemKey1 = item[key1];
          if (seen.has(itemKey) && seen.has(itemKey1)) {
            return false;
          }
          seen.add(itemKey);
          seen.add(itemKey1);
          return true;
        })
      },
      async handleConfirm() {
        if (this.isFormula) {
          const formulaChoose = await this.formulaList.filter(el => {
            return el.number == this.chooseFormula;
          });
          this.formulaNode.setAttribute("relation-formula-id", formulaChoose[0].dataId);
          this.formulaNode.innerText = `(${formulaChoose[0].number})`
          this.formulaNode.dataset.relationFormulaId = `${formulaChoose[0].dataId}`;
          this.formulaNode.dataset.formulaLatex = `${formulaChoose[0].latex}`;

          const formulaContent = {
            formulaNumber: formulaChoose[0].number,
            latex: formulaChoose[0].latex,
            dataId: formulaChoose[0].dataId,
            textContent: formulaChoose[0].name,
          }
          const formData = new FormData();
          formData.append("docNo", this.$store.state.xmleditor.docInfo.id);
          formData.append("docType", "TEMPLATE");
          formData.append("id", Number.parseInt(this.variableAtt.variableId));
          formData.append("variableContent", JSON.stringify(formulaContent));
          saveVeriableValue(formData).then(res => {
            this.handleClose();
          })
          this.handleClose();
          return;
        }
        if (this.isPic) {
          const picChoose = await this.picList.filter(el => {
            return el.number == this.choosePic;
          });
          this.formulaNode.innerText = `图 ${picChoose[0].number}`
          const picContent = {
            picNumber: picChoose[0].number,
            dataId: picChoose[0].dataId,
            textContent: picChoose[0].name,
          }
          const formData = new FormData();
          formData.append("docNo", this.$store.state.xmleditor.docInfo.id);
          formData.append("docType", "TEMPLATE");
          formData.append("id", Number.parseInt(this.variableAtt.variableId));
          formData.append("variableContent", JSON.stringify(picContent));
          saveVeriableValue(formData).then(res => {
            this.handleClose();
          })
          this.handleClose();
          return;
        }
        if (this.isTable) {
          const tableChoose = await this.tableList.filter(el => {
            return el.number == this.chooseTable;
          });
          this.formulaNode.innerText = `表 ${tableChoose[0].number}`
          const tableContent = {
            tableNumber: tableChoose[0].number,
            dataId: tableChoose[0].dataId,
            textContent: tableChoose[0].name,
          }
          const formData = new FormData();
          formData.append("docNo", this.$store.state.xmleditor.docInfo.id);
          formData.append("docType", "TEMPLATE");
          formData.append("id", Number.parseInt(this.variableAtt.variableId));
          formData.append("variableContent", JSON.stringify(tableContent));
          saveVeriableValue(formData).then(res => {
            this.handleClose();
          })
          this.handleClose();
          return;
        }
        if (this.variableAtt.dataType === 'variable_formula') {
          this.$store.commit('xmleditor/SET_EDITING_FORMULA', { id: this.variableAtt.dataId, type: 'variable_formula' })
          const iframe = this.$refs.formulaRef
          iframe.contentWindow.postMessage('save_variable_formula', '*')
          this.handleClose();
        } else if (this.variableAtt.dataType === 'variable_inline_formula') {
          this.$store.commit('xmleditor/SET_EDITING_FORMULA', { id: this.variableAtt.dataId, type: 'variable_formula' })
          const iframe = this.$refs.formulaRef
          iframe.contentWindow.postMessage('save_variable_inline_formula', '*')
          this.handleClose();
        } else if (this.variableAtt.dataType === 'variable_string') {
          if (!this.inputVal) {
            this.$message.error('请输入内容')
            return;
          }
          const variableNode = tinymce.activeEditor.dom.select(`span[data-id="${this.variableAtt.dataId}"]`)
          setTimeout(() => {
            variableNode[0].innerText = this.inputVal;
            variableNode[0].dataset.content = this.inputVal;
            this.handleClose();
          });
          //主要结构 变量 需要替换裕度汇总表表头
          const mainStructorObj = await this.$store.state.xmleditor.allVariables.filter(el => {
            return el.variableCode == 'mainStructure'
          })
          const algoAllTableObj = await this.$store.state.xmleditor.allVariables.filter(el => {
            return el.variableCode == 'msSummary'
          })
          const doc = tinymce.activeEditor.getDoc();
          if (this.variableAtt.variableId == mainStructorObj[0]?.id) {
            if (algoAllTableObj[0]) {
              const algoALLTableNode = doc.querySelector(`[data-variable-id="${algoAllTableObj[0].id}"]`);
              const algoALLTableNodeCaption = algoALLTableNode.querySelector('caption');
              let captionP = algoALLTableNodeCaption.querySelector('p');
              captionP.innerText = `${this.inputVal.trim()}结构静强度裕度汇总表`;
            }
          }
        } else if (this.variableAtt.dataType === 'variable_img') {
          this.handleInsertImg()
          this.handleClose()
        } else if (this.variableAtt.dataType === 'variable_string_quote') {
          if (!this.inputVal) {
            this.$message.error('请输入文件名')
            return;
          }
          if (!this.codeVal) {
            this.$message.error('请输入文件Code')
            return;
          }
          // 保存变量值
          const variableContent = {
            code: this.codeVal,
            name: this.inputVal
          }
          const formData = new FormData();
          formData.append("docNo", this.$store.state.xmleditor.docInfo.docNo);
          formData.append("id", Number.parseInt(this.variableAtt.variableId));
          formData.append("variableContent", JSON.stringify(variableContent));
          saveVeriableValue(formData).then(async res => {
            if (res?.data.length) {
              var editor = tinymce.activeEditor;
              const datas = res.data[0];
              let str = ''
              let exsitData = await datas.variableContent.filter(el => {
                return el.code == this.codeVal && el.name == this.inputVal;
              })
              let first = true;
              const node = editor.getDoc()?.querySelector(`span[data-type="variable_string_summary"]`)
              const hasSpan = node.querySelector('span') !== null;
              console.log(hasSpan)
              if (!hasSpan) {
                let algoSpan = `<span style="padding-left:${0.8}cm;">${this.codeVal}&nbsp;&nbsp;&nbsp;&nbsp;${this.inputVal}</span><br />`;
                str += algoSpan;
                node.innerHTML = str
              } else {
                if (exsitData.length < 2) {
                  let algoSpan = `<span style="padding-left:${0.8}cm;">${this.codeVal}&nbsp;&nbsp;&nbsp;&nbsp;${this.inputVal}</span><br />`;
                  str += algoSpan;
                  node.innerHTML += str
                }
              }


            }
            const variableNode = tinymce.activeEditor.dom.select(`span[data-id="${this.variableAtt.dataId}"]`)
            variableNode[0].innerText = `${this.codeVal}\xa0\xa0\xa0\xa0<<${this.inputVal}>>`;
            variableNode[0].dataset.content = `${this.codeVal}\xa0\xa0\xa0\xa0<<${this.inputVal}>>`;
            this.handleClose();
          })
        } else if (this.variableAtt.dataType === 'variable_string_relationFileName') {
          const variableNode = tinymce.activeEditor.dom.select(`span[data-id="${this.variableAtt.dataId}"]`)
          if (this.currentRow) {
            variableNode[0].innerText = `${this.currentRow?.fileCode}    ${this.currentRow?.fileName}`;
          }
          this.handleClose();
        }
      },
      handleMessage(event) {
        if (event.cmd === 'variableFormulaInsertContent') {
          const { data, latex } = event.value;
          var editor = tinymce.activeEditor;
          var image = new Image()
          image.src = data.img
          const that = this
          image.onload = function () {
            const nodeId = that.$store.state.xmleditor.editingFormulaId
            const node = editor.getDoc()?.querySelector(`[data-id="${nodeId}"]`)
            editor.selection.select(node.parentNode);
            editor.execCommand('Delete');
            const width = parseInt(image.width)
            const height = parseInt(image.height)
            editor.insertContent(`
            <div class="formula" 
              contenteditable="false" 
              data-type="formula" 
              data-latex="${latex}"
              data-unit=""
              data-formula-number="1" 
              data-id="${uuid()}"
              data-image-width="${width}" 
              data-image-height="${height}"
            >
              <div class="img-wrapper irremovable" data-formula-number="1">
                <img contenteditable="true" 
                  style="margin-left: calc(50% - ${width / 4}px);" 
                  width="${width / 2}"
                  height="${height / 2}"
                  src="${image.src}" 
                  data-img-latex="${latex}">
                <div class="formula-unit irremovable" contenteditable="false"></div>
                <div class="dotline irremovable" contenteditable="false" style="height: ${height / 4}px"></div>
              </div>
            </div>
        `)
            setTimeout(() => editor.fire('updateFormulaNumber'))
          }
        } else if (event.cmd === 'variableInlineFormulaInsertContent') {
          var image = new Image()
          const that = this
          const { data, latex } = event.value;
          var editor = tinymce.activeEditor;
          image.src = data.img
          image.onload = function () {
            const nodeId = that.$store.state.xmleditor.editingFormulaId
            const node = editor.getDoc()?.querySelector(`[data-id="${nodeId}"]`)
            editor.selection.select(node);
            editor.execCommand('Delete');
            const width = parseInt(image.width / 2)
            const height = parseInt(image.height / 2)
            editor.insertContent(`
            <img contenteditable="true" 
              data-type="inline_formula"
              data-id="${uuid()}"
              width="${width}"
              height="${height}"
              src="${image.src}" 
              data-latex="${latex}">
            `)
          }
        }
      },
      async handleAllReplace() {
        if (!this.inputVal) {
          this.$message.error('请输入内容')
          return;
        }
        tinymce.activeEditor.dom.select(`[data-type='${this.variableAtt.dataType}']`).forEach((node) => {
          if (node.innerText === this.originVal) {
            node.innerText = this.inputVal
          }
        })
        //主要结构 变量 需要替换裕度汇总表表头
        const mainStructorObj = await this.$store.state.xmleditor.allVariables.filter(el => {
          return el.variableCode == 'mainStructure'
        })
        const algoAllTableObj = await this.$store.state.xmleditor.allVariables.filter(el => {
          return el.variableCode == 'msSummary'
        })
        const doc = tinymce.activeEditor.getDoc();
        if (this.variableAtt.variableId == mainStructorObj[0]?.id) {
          if (algoAllTableObj[0]) {
            const algoALLTableNode = doc.querySelector(`[data-variable-id="${algoAllTableObj[0].id}"]`);
            const algoALLTableNodeCaption = algoALLTableNode.querySelector('caption');
            let captionP = algoALLTableNodeCaption.querySelector('p');
            captionP.innerText = `${this.inputVal.trim()}结构静强度裕度汇总表`;
          }
        }
        this.handleClose()
      },
      handleImgSuccess(response, file) {
        console.log(response, file)
        this.imgSrc += response.data
      },
      handleInsertImg() {
        var image = new Image()
        var editor = tinymce.activeEditor;
        image.src = this.imgSrc
        const that = this
        image.onload = function () {
          const nodeId = that.variableAtt.dataId
          const node = editor.getDoc()?.querySelector(`[data-id="${nodeId}"]`)
          console.log(node, 'xxxxx')
          editor.selection.select(node.parentNode);
          editor.execCommand('Delete');
          const width = parseInt(image.width)
          const height = parseInt(image.height)
          editor.insertContent(`
          <div data-type="figure" 
          data-block-id="${uuid()}" 
          data-id="${uuid()}" 
          data-figure-annex-number="" 
          data-number="1" 
          class="data-content-image-wrapper" 
          contenteditable="true" 
          container="">
            <p class="image-wrapper">
              <img src="${image.src}" width="${width}" height="${height}" alt="    图题    ">
            </p>
            <p data-id="${uuid()}" data-lang="zh" data-figure-annex-number="" data-number="1" class="data-content-image-caption zh">     图题</p>
          </div>
        `)
          refreshFigureNumbers(editor)
        }

      },
      handleClose() {
        this.dialogVisible = false;
      },
    },
  };
</script>

<style scoped>
  .variable-class {
    font-style: italic;
    text-decoration: underline;
    color: blue;
  }

  .replace-img {
    text-align: center;
  }

  .ins-table {
    width: 100%;
  }

  ::v-deep .el-dialog {
    min-width: 800px;
  }

  ::v-deep .el-dialog__body {
    padding-top: 0;
    padding-bottom: 10px;
  }
</style>